//
//  DetailViewController.m
//  DSApp
//
//  Created by Vladimir Aguilar on 2011-09-27.
//  Copyright 2011 Hem. All rights reserved.
//

#import "DetailViewController.h"
#import "RootViewController.h"
#import "DSAppAppDelegate.h"


@implementation DetailViewController

@synthesize toolbar, popoverController, detailItem, detailDescriptionLabel, rootViewController, titleLabel, cameraRollBtn, saveBtn, searchBar;

@synthesize name, surName, address, phoneNr,customerPhoto;




#pragma mark -
#pragma mark Camera interaction
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	
    UITouch *touch = [touches anyObject];
	
    if ([touch view] == customerPhoto)
    {
		//Take picture
		if ([UIImagePickerController isSourceTypeAvailable:
			 UIImagePickerControllerSourceTypeCamera])
		{
			UIImagePickerController *imagePicker =
			[[UIImagePickerController alloc] init];
			imagePicker.delegate = self;
			imagePicker.sourceType = 
			UIImagePickerControllerSourceTypeCamera;
			imagePicker.mediaTypes = [NSArray arrayWithObjects:
									  (NSString *) kUTTypeImage,
									  nil];
			imagePicker.allowsEditing = NO;
			[self presentModalViewController:imagePicker 
									animated:YES];
			[imagePicker release];
			newMedia = YES;
		}
		
		NSLog(@"Take Picture");
    }
	

	
}


- (void) useSavedPhotos
{
	
	if (popoverController.popoverVisible) {
		[popoverController dismissPopoverAnimated:YES];
		
	}
	
	//popoverController.
	if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum] && !popoverController.popoverVisible)
    {
		
	UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
	imagePicker.delegate = self;
	
	imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
	imagePicker.mediaTypes = [NSArray arrayWithObjects:(NSString *) kUTTypeImage,nil];
	imagePicker.allowsEditing = YES;	
	
	popoverController = [[UIPopoverController alloc] initWithContentViewController:imagePicker];
	[popoverController presentPopoverFromBarButtonItem:cameraRollBtn permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

	[imagePicker release];
		
		newMedia = NO;
    }
	

	
}


-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
	//Set image for current customer	
	NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
	[popoverController dismissPopoverAnimated:YES];


	
	if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
		
		//convert from PNG to NSData and set it reade for saving 
		//Reminder other method available for JPG
		NSData *imageData = UIImagePNGRepresentation(image);
		[detailItem setValue:imageData forKey:@"customerPhoto"];

		//Set image on 
		customerPhoto.image = image;
		
		//Save edited image
		saveBtn.enabled = true;
		
		
		//Save if it is new image
        if (newMedia)
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:finishedSavingWithError:contextInfo:), nil);
	}
	else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
	{
		// Code here to support video if enabled
	}
		
	

}

-(void)image:(UIImage *)image finishedSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
	if (error) {
        UIAlertView *alert = [[UIAlertView alloc]
							  initWithTitle: @"Save failed"
							  message: @"Failed to save image"\
							  delegate: nil
							  cancelButtonTitle:@"OK"
							  otherButtonTitles:nil];
        [alert show];
        [alert release];
	}
	

}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
	[popoverController dismissPopoverAnimated:YES];
	


}


#pragma mark -
#pragma mark Object insertion

- (IBAction)insertNewObject:(id)sender {
	
	[self.rootViewController insertNewObject:sender];
	DSAppAppDelegate *appDelegate = (DSAppAppDelegate *)[[UIApplication sharedApplication] delegate];
	RootViewController *rootDelegate = [[RootViewController alloc] initWithStyle:UITableViewStylePlain];
	rootDelegate.managedObjectContext = [appDelegate managedObjectContext];
	[rootDelegate insertNewObject:sender];

}

- (void) saveData {
	//Save information
	//Update Mananged Object
	[detailItem setValue:name.text	  forKey:@"name"];
	[detailItem setValue:surName.text forKey:@"surName"];
	[detailItem setValue:address.text forKey:@"address"];
	[detailItem setValue:phoneNr.text forKey:@"phoneNr"];
	
	NSError *error = nil;
	DSAppAppDelegate *appDelegate = (DSAppAppDelegate *)[[UIApplication sharedApplication] delegate];
	NSManagedObjectContext *managedObjectContext = [appDelegate managedObjectContext];
	
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            /*
             Replace this implementation with code to handle the error appropriately.
             
             abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
             */
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } 
	}
	
	/*
	//Pass the information to a temp object a rootViewController
	rootViewController.newCustomer.name = name.text;
	rootViewController.newCustomer.sureName = surName.text;
	rootViewController.newCustomer.address = address.text;
	rootViewController.newCustomer.phoneNr = phoneNr.text;
	 */
	
	
	

}
- (IBAction)saveChanges:(id)sender{
	
	//Save Data that is displayed on the screen
	[self saveData];
	
	[tempEdit resignFirstResponder];
	detailDescriptionLabel.text=@"Saved";
	saveBtn.enabled=false;
	

 
}

#pragma mark -
#pragma mark Object Search

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{


	
	DSAppAppDelegate *appDelegate = (DSAppAppDelegate *)[[UIApplication sharedApplication] delegate];
	
    NSManagedObjectContext *context = [appDelegate managedObjectContext];
    NSEntityDescription *entityDesc = [NSEntityDescription
									   entityForName:@"Customer" 
									   inManagedObjectContext:context];
	
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDesc];
	
	//[CD]Case insensetive and diacritic(Such as an acute accent (á), a grave accent (à) and a cedilla (ç))
    NSPredicate *pred =[NSPredicate predicateWithFormat:@"(name = [CD]%@) OR (surName = [CD]%@)",self.searchBar.text];
	
	
	//NSPredicate *pred = [NSPredicate predicateWithFormat:@"(SELF contains[cd] %@)", self.searchBar.text];
	[request setPredicate:pred];
    
	NSManagedObject *matches = nil;
    NSError *error;
    NSArray *objects = [context executeFetchRequest:request 
											  error:&error];
    if ([objects count] == 0) {
		detailDescriptionLabel.text = @"No matches";
    } else {
		//matches = [objects objectAtIndex:0];
		//address.text = [matches valueForKey:@"address"];
		//phone.text = [matches valueForKey:@"phone"];
		detailDescriptionLabel.text = [NSString stringWithFormat:
									   @"%d matches found", [objects count]];
    }
    [request release];
	
	//NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%@ contains[c] %@)", self.searchBar.text];
	//[rootViewController.fetchedResultsController.fetchRequest setPredicate:predicate];
	
	
	//
	
	/*
	DSAppAppDelegate *appDelegate = (DSAppAppDelegate *)[[UIApplication sharedApplication] delegate];
	//NSManagedObjectModel   * model    = [[NSApp delegate] managedObjectModel];
	//NSDictionary           * entities = [model entitiesByName];
	//NSEntityDescription    * entity   = [entities valueForKey:@"Post"];
	
	//NSPredicate * predicate;
	//predicate = [NSPredicate predicateWithFormat:@"creationDate > %@", date];
	//NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%@ contains[c] %@)", searchBar.text];

	
	NSSortDescriptor * sort = [[NSortDescriptor alloc] initWithKey:@"title"];
	NSArray * sortDescriptors = [NSArray arrayWithObject: sort];
	
	NSFetchRequest * fetch = [[NSFetchRequest alloc] init];
	[fetch setEntity: entity];
	[fetch setPredicate: predicate];
	[fetch setSortDescriptors: sortDescriptors];
	
	NSArray * results = [context executeFetchRequest:fetch error:nil];
	[sort release];
	[fetch release];
	*/
	
	//
	//[self findContact];
	//[rootViewController.tableView reloadData];
	//[rootViewController.fetchRequest setPredicate:predicate];
	
}

- (void) findContact
{
	//coreDataAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
	DSAppAppDelegate *appDelegate = (DSAppAppDelegate *)[[UIApplication sharedApplication] delegate];

    NSManagedObjectContext *context = [appDelegate managedObjectContext];
    NSEntityDescription *entityDesc = [NSEntityDescription
									   entityForName:@"Customer" 
									   inManagedObjectContext:context];
	
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDesc];
	
    NSPredicate *pred =[NSPredicate 
						predicateWithFormat:@"(name = %@)", name.text];
    [request setPredicate:pred];
    
	NSManagedObject *matches = nil;
    NSError *error;
    NSArray *objects = [context executeFetchRequest:request 
											  error:&error];
    if ([objects count] == 0) {
		detailDescriptionLabel.text = @"No matches";
    } else {
		//matches = [objects objectAtIndex:0];
		//address.text = [matches valueForKey:@"address"];
		//phone.text = [matches valueForKey:@"phone"];
		detailDescriptionLabel.text = [NSString stringWithFormat:
					   @"%d matches found", [objects count]];
    }
    [request release];
	
}






#pragma mark -
#pragma mark TextField delegates
//Displays Keyboard when any textfield touch upon
- (void)textFieldDidBeginEditing:(UITextField *)textField{
	
	tempEdit = textField;
}

//Hiddes keyboard when hit return button
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
	//[self.rootViewController insertNewObject:sender];	

	[self saveData];
	[theTextField resignFirstResponder];
	 saveBtn.enabled=false;

	
	return YES;
}



- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
	
	//If any changed done Enable the save button in the nav bar.
	saveBtn.enabled=true;
	
	/*
	//Need for the other?
	if (textField.tag == 0){
		NSCharacterSet *nonLetterSet = [[NSCharacterSet letterCharacterSet] invertedSet];
		return ([string stringByTrimmingCharactersInSet:nonLetterSet].length > 0);	
	}
	if (textField.tag == 1){
		NSCharacterSet *nonLetterSet = [[NSCharacterSet letterCharacterSet] invertedSet];
		return ([string stringByTrimmingCharactersInSet:nonLetterSet].length > 0);	
	}
	
	if (textField.tag == 2)
		return true;
	*/
	
	//Accept only numbers.
	if (textField.tag == 3){
		NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
		return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);
	}
	return YES;
}



- (void)textFieldDidEndEditing:(UITextField *)textField{
	//saveBtn.enabled=false;

}


#pragma mark -
#pragma mark Managing the detail item

/*
 When setting the detail item, update the view and dismiss the popover controller if it's showing.
 */
- (void)setDetailItem:(NSManagedObject *)managedObject {
    
	if (detailItem != managedObject) {
		[detailItem release];
		detailItem = [managedObject retain];
		
        // Update the view.
        [self configureView];
	}
    
    if (self.popoverController != nil) {
        [self.popoverController dismissPopoverAnimated:YES];
		

    }		
}



- (void)configureView {
    // Update the user interface for the detail item.
   
	detailDescriptionLabel.text = [[detailItem valueForKey:@"timeStamp"] description];
	
	name.text	 = [[detailItem valueForKey:@"name"] description];
	surName.text = [[detailItem valueForKey:@"surName"] description];
	address.text = [[detailItem valueForKey:@"address"] description];
	phoneNr.text = [[detailItem valueForKey:@"phoneNr"] description];
	
	//Get photo from data
	NSData *dataBytes =[detailItem valueForKey:@"customerPhoto"];
	customerPhoto.image = [UIImage imageWithData:dataBytes];
	
	[self.popoverController dismissPopoverAnimated:YES];



	
}


#pragma mark -
#pragma mark Split view support

- (void)splitViewController: (UISplitViewController*)svc willHideViewController:(UIViewController *)aViewController withBarButtonItem:(UIBarButtonItem*)barButtonItem forPopoverController: (UIPopoverController*)pc {
    
    barButtonItem.title = @"Elever";
    NSMutableArray *items = [[toolbar items] mutableCopy];
    [items insertObject:barButtonItem atIndex:0];
	[toolbar setItems:items animated:YES];
    [items release];
    self.popoverController = pc;
}


// Called when the view is shown again in the split view, invalidating the button and popover controller.
- (void)splitViewController: (UISplitViewController*)svc willShowViewController:(UIViewController *)aViewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem {
    
    NSMutableArray *items = [[toolbar items] mutableCopy];
    [items removeObjectAtIndex:0];
    [toolbar setItems:items animated:YES];
    [items release];
    self.popoverController = nil;
	
}


#pragma mark -
#pragma mark Rotation support

// Ensure that the view controller supports rotation and that the split view can therefore show in both portrait and landscape.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}


- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
}


#pragma mark -
#pragma mark View lifecycle


 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
    [super viewDidLoad];
}
 

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
	self.customerPhoto = nil;
	self.popoverController = nil;
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)dealloc {
	
    [popoverController release];
    [toolbar release];
	
	[name release];
	[surName release];
	[address release];
	[phoneNr release];
	[customerPhoto release];
	[cameraRollBtn release];
	[saveBtn release];
	[searchBar release];
	
	[detailItem release];
	[detailDescriptionLabel release];
    
	[super dealloc];
}	


@end
